package com.google.code.gronono.gps.ui.panels.pages.tree;

import java.awt.Component;
import java.io.File;
import java.net.URL;

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;

import com.google.code.gronono.commons.i18n.BundleKey;
import com.google.code.gronono.commons.i18n.BundleName;
import com.google.code.gronono.gps.model.SortedFile;

/**
 * Fournisseur de rendu utilisé pour les arbres.
 */
@BundleName(value = "com.google.code.gronono.gps.gui")
public class SortedFileTreeRender extends DefaultTreeCellRenderer {
	/** serialVersionUID. */
	private static final long serialVersionUID = 7299274028091662770L;

	/** Icône ok. */
	@BundleKey(value = "result.page.ok.icon")
	private static String OK_ICON;
	/** Icône ko. */
	@BundleKey(value = "result.page.ko.icon")
	private static String KO_ICON;

	/** Icône représentant un franc succès ;). */
	private final Icon okIcon;
	/** Icône représentant une belle déroute :(. */
	private final Icon koIcon;

	/** Arbre cible. */
	private final JTree dstTree;

	/**
	 * Constructeur.
	 * @param dstTree L'arbre cible.
	 */
	public SortedFileTreeRender(final JTree dstTree) {
		final URL urlOk = this.getClass().getClassLoader().getResource(OK_ICON);
		this.okIcon = new ImageIcon(urlOk);
		final URL urlKo = this.getClass().getClassLoader().getResource(KO_ICON);
		this.koIcon = new ImageIcon(urlKo);
		this.dstTree = dstTree;
	}

	/* (non-Javadoc)
	 * @see javax.swing.tree.DefaultTreeCellRenderer#getTreeCellRendererComponent(javax.swing.JTree, java.lang.Object, boolean, boolean, boolean, int, boolean)
	 */
	@Override
	public Component getTreeCellRendererComponent(final JTree tree, final Object value,
			final boolean sel, final boolean expanded, final boolean leaf, final int row,
			final boolean focus) {
		super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, focus);

		// Récupération du model associé à la cellule
		final SortedFile sortedFile = (SortedFile) ((DefaultMutableTreeNode)value).getUserObject();
		// Et du fichier associé
		File file = sortedFile.getSrcFile();
		if (tree == dstTree){
			file = sortedFile.getDstFile();
		}

		// Cas traitement ok
		Icon icon = okIcon;
		if (!leaf || file.isDirectory()) {
			icon = super.getIcon();
		}
		// Cas traitement ko
		String label = file.getName();
		if (sortedFile.hasError()) {
			label += " : " + sortedFile.getErrorMsg();
			icon = koIcon;
		}

		setText(label);
		setIcon(icon);

		return this;
	}

}
